<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>轮胎可视化管理系统</title>
    <!-- 引入 Bootstrap CSS -->
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
    <!-- 引入 jQuery 和 jQuery UI 用于自动补全 -->
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.0/themes/smoothness/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://code.jquery.com/ui/1.13.0/jquery-ui.min.js"></script>
    <style>
        /* 导航栏样式修复 - 确保深色主题 */
        .navbar {
            background-color: #343a40 !important; /* 深灰色背景 */
            border-bottom: 1px solid #4b545c;
        }

        .navbar-brand, .navbar-nav .nav-link {
            color: #ffffff !important; /* 白色文字 */
        }

        .navbar-nav .nav-link:hover,
        .navbar-nav .nav-link:focus {
            color: #f8f9fa !important; /* 悬停时更亮的白色 */
            background-color: rgba(255, 255, 255, 0.1);
        }

        .navbar-nav .nav-link.active {
            color: #ffffff !important;
            font-weight: bold;
            background-color: rgba(255, 255, 255, 0.2);
            border-radius: 4px;
        }

        .navbar-toggler {
            border-color: rgba(255, 255, 255, 0.5);
        }

        .navbar-toggler-icon {
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='30' height='30' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%28255, 255, 255, 0.8%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e");
        }

        /* 原有样式保持不变 */
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Microsoft YaHei', Arial, sans-serif; background-color: #f5f5f5; padding: 0; }
        .container { max-width: 1200px; margin: 20px auto; background: white; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); padding: 20px; }
        .header { text-align: center; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid #eee; }
        .search-box { display: flex; justify-content: center; margin-bottom: 20px; gap: 10px; }
        .search-box input { padding: 10px; border: 1px solid #ddd; border-radius: 5px; width: 300px; font-size: 16px; }
        .search-box button { padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; }
        .search-box button:hover { background: #0056b3; }

        .trailer-container {
            position: relative;
            width: 900px;
            height: 700px;
            margin: 0 auto;
            border: 2px solid #333;
            border-radius: 10px;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            overflow: hidden;
        }

        .trailer-body {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 600px;
            height: 150px;
            background: #6c757d;
            border-radius: 15px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }

        .axle {
            position: absolute;
            width: 500px;
            height: 6px;
            background: #495057;
            left: 50px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.3);
        }

        .tire-position {
            position: absolute;
            width: 70px;
            height: 70px;
            border-radius: 50%;
            border: 3px solid #333;
            cursor: pointer;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            font-size: 10px;
            font-weight: bold;
            text-align: center;
            transition: all 0.3s ease;
            background: rgba(255, 255, 255, 0.95);
            box-shadow: 0 3px 6px rgba(0,0,0,0.16);
            z-index: 5;
        }

        .tire-position.has-tire {
            background: #28a745;
            color: white;
            border-color: #1e7e34;
        }

        .tire-position.has-tire.warning {
            background: #ffc107;
            color: black;
            border-color: #e0a800;
        }

        .tire-position.has-tire.danger {
            background: #dc3545;
            color: white;
            border-color: #c82333;
        }

        .tire-position:hover {
            transform: scale(1.15);
            z-index: 10;
            box-shadow: 0 6px 20px rgba(0,0,0,0.25);
        }

        .tire-number {
            font-size: 12px;
            font-weight: bold;
            margin-bottom: 2px;
        }

        .tire-position-label {
            font-size: 9px;
            opacity: 0.9;
        }

        .empty-tire {
            font-size: 9px;
            color: #666;
        }

        .info-panel {
            position: fixed;
            top: 50%;
            right: 20px;
            transform: translateY(-50%);
            width: 350px;
            background: white;
            border: 1px solid #ddd;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            padding: 20px;
            display: none;
            z-index: 1000;
        }

        .info-panel h3 {
            margin-bottom: 15px;
            color: #333;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }

        .info-item {
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
        }

        .info-label {
            font-weight: bold;
            color: #666;
            min-width: 100px;
        }

        .info-value {
            color: #333;
            flex: 1;
            text-align: right;
        }

        .no-tire {
            color: #999;
            font-style: italic;
            text-align: center;
            margin: 10px 0;
        }

        .close-btn {
            position: absolute;
            top: 10px;
            right: 15px;
            background: none;
            border: none;
            font-size: 20px;
            cursor: pointer;
            color: #999;
        }

        .close-btn:hover {
            color: #333;
        }

        .action-btn {
            margin-top: 15px;
            padding: 8px 15px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            width: 100%;
        }

        .action-btn:hover {
            background: #0056b3;
        }

        .axle-label {
            position: absolute;
            left: 20px;
            font-weight: bold;
            color: #495057;
            font-size: 14px;
            background: rgba(255,255,255,0.8);
            padding: 2px 8px;
            border-radius: 4px;
        }

        .status-legend {
            display: flex;
            justify-content: center;
            margin-top: 20px;
            gap: 15px;
        }

        .status-item {
            display: flex;
            align-items: center;
            gap: 5px;
            font-size: 12px;
        }

        .status-color {
            width: 15px;
            height: 15px;
            border-radius: 50%;
            border: 1px solid #333;
        }

        .status-normal { background: #28a745; }
        .status-warning { background: #ffc107; }
        .status-danger { background: #dc3545; }
        .status-empty { background: rgba(255, 255, 255, 0.95); }

        .loading {
            display: none;
            text-align: center;
            padding: 20px;
            color: #666;
        }

        .error-message {
            display: none;
            text-align: center;
            padding: 20px;
            color: #dc3545;
            background: #f8d7da;
            border-radius: 5px;
            margin: 10px 0;
        }

        /* 自动补全样式 */
        .ui-autocomplete {
            max-height: 200px;
            overflow-y: auto;
            overflow-x: hidden;
            z-index: 1000;
        }
        .ui-autocomplete-loading {
            background: white url('https://code.jquery.com/ui/1.13.0/themes/smoothness/images/ui-anim_basic_16x16.gif') right center no-repeat;
            background-size: 16px 16px;
        }
    </style>
</head>
<body>
<!-- 导航栏 - 使用深色主题 -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <div class="container-fluid">
        <a class="navbar-brand" href="/api/tires">轮胎管理系统</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav me-auto">
                <li class="nav-item">
                    <a class="nav-link" href="/api/tires">轮胎列表</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/api/tires/batch-add">批量添加轮胎</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/api/tires/usage">查询使用记录</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="/api/tires/visualization/">轮胎可视化</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/api/tires/statistics">轮胎统计</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/api/tires/cost-statistics">费用统计报表</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/api/tires/settlement">费用结算</a>
                </li>
            </ul>
        </div>
    </div>
</nav>

<div class="container">
    <div class="header">
        <h1>🚛 轮胎可视化管理系统</h1>
    </div>

    <div class="search-box">
        <input type="text" id="plateInput" placeholder="请输入拖车车牌号，支持自动补全">
        <button onclick="loadTrailer()">加载轮胎信息</button>
    </div>

    <div class="loading" id="loadingIndicator">
        <p>正在加载轮胎数据...</p>
    </div>

    <div class="error-message" id="errorMessage"></div>

    <div class="trailer-container" id="trailerContainer">
        <div class="trailer-body"></div>

        <div class="axle" style="top: 250px;">
            <div class="axle-label">1轴</div>
        </div>
        <div class="axle" style="top: 320px;">
            <div class="axle-label">2轴</div>
        </div>
        <div class="axle" style="top: 390px;">
            <div class="axle-label">3轴</div>
        </div>
        <div class="axle" style="top: 460px;">
            <div class="axle-label">4轴</div>
        </div>
        <div class="axle" style="top: 530px;">
            <div class="axle-label">5轴</div>
        </div>
        <div class="axle" style="top: 600px;">
            <div class="axle-label">6轴</div>
        </div>
    </div>

    <div class="status-legend">
        <div class="status-item">
            <div class="status-color status-normal"></div>
            <span>正常 (&lt;10万公里)</span>
        </div>
        <div class="status-item">
            <div class="status-color status-warning"></div>
            <span>警告 (10-20万公里)</span>
        </div>
        <div class="status-item">
            <div class="status-color status-danger"></div>
            <span>危险 (&gt;20万公里)</span>
        </div>
        <div class="status-item">
            <div class="status-color status-empty"></div>
            <span>无轮胎</span>
        </div>
    </div>

    <div class="info-panel" id="infoPanel">
        <button class="close-btn" onclick="closeInfoPanel()">&times;</button>
        <h3>轮胎详细信息</h3>
        <div id="tireDetails"></div>
    </div>
</div>

<!-- 引入 Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
    class TireVisualization {
        constructor() {
            this.currentPlate = '';
            this.tireData = [];
            this.positionCoordinates = {
                1: { '左外': {x: 150, y: 240}, '左内': {x: 250, y: 240}, '右内': {x: 350, y: 240}, '右外': {x: 450, y: 240} },
                2: { '左外': {x: 150, y: 310}, '左内': {x: 250, y: 310}, '右内': {x: 350, y: 310}, '右外': {x: 450, y: 310} },
                3: { '左外': {x: 150, y: 380}, '左内': {x: 250, y: 380}, '右内': {x: 350, y: 380}, '右外': {x: 450, y: 380} },
                4: { '左外': {x: 150, y: 450}, '左内': {x: 250, y: 450}, '右内': {x: 350, y: 450}, '右外': {x: 450, y: 450} },
                5: { '左外': {x: 150, y: 520}, '左内': {x: 250, y: 520}, '右内': {x: 350, y: 520}, '右外': {x: 450, y: 520} },
                6: { '左外': {x: 150, y: 590}, '左内': {x: 250, y: 590}, '右内': {x: 350, y: 590}, '右外': {x: 450, y: 590} }
            };
        }

        async loadTrailer(plateNumber) {
            try {
                this.showLoading(true);
                this.hideError();

                console.log('正在请求数据，车牌号:', plateNumber);

                const response = await fetch(`/api/tires/visualization/trailer/${encodeURIComponent(plateNumber)}`);

                console.log('响应状态:', response.status);

                if (!response.ok) {
                    if (response.status === 404) {
                        throw new Error(`未找到车牌号为 ${plateNumber} 的拖车数据`);
                    } else {
                        throw new Error(`服务器错误: ${response.status}`);
                    }
                }

                const data = await response.json();
                console.log('API返回数据:', data);

                this.currentPlate = plateNumber;
                this.tireData = this.processApiData(data);

                console.log('处理后的轮胎数据:', this.tireData);

                this.renderTrailer();
            } catch (error) {
                console.error('加载数据错误:', error);
                this.showError('加载轮胎数据失败：' + error.message);
            } finally {
                this.showLoading(false);
            }
        }

        processApiData(apiData) {
            console.log('原始API数据:', apiData);

            let positions = [];

            // 处理不同的数据结构
            if (apiData.positions && Array.isArray(apiData.positions)) {
                positions = apiData.positions;
            } else if (Array.isArray(apiData)) {
                positions = apiData;
            } else if (apiData.tires && Array.isArray(apiData.tires)) {
                positions = apiData.tires;
            } else {
                positions = Object.values(apiData).filter(item =>
                    item && (item.axleNumber !== undefined || item.position !== undefined)
                );
            }

            console.log('提取的位置数据:', positions);

            const result = positions.map(position => {
                const axleNumber = position.axleNumber ||
                    (position.position ? parseInt(position.position.split('轴')[0]) : null) ||
                    (position.axle ? parseInt(position.axle) : null);

                const tirePosition = position.tirePosition ||
                    (position.position ? position.position.split('轴')[1] : null) ||
                    position.positionName;

                console.log(`处理位置: axleNumber=${axleNumber}, tirePosition=${tirePosition}`);

                if (!axleNumber || !tirePosition) {
                    console.warn('无法解析位置信息:', position);
                    return null;
                }

                const coords = this.positionCoordinates[axleNumber] &&
                    this.positionCoordinates[axleNumber][tirePosition];

                if (!coords) {
                    console.warn(`未找到坐标信息: ${axleNumber}轴${tirePosition}`);
                    return null;
                }

                const processedPosition = {
                    axleNumber: axleNumber,
                    tirePosition: tirePosition,
                    positionKey: `${axleNumber}轴${tirePosition}`,
                    x: coords.x,
                    y: coords.y,
                    hasTire: false,
                    tireInfo: null
                };

                // 检查是否有轮胎信息 - 确保包含ID字段
                if (position.tireNumber || position.tireInfo || position.id) {
                    processedPosition.hasTire = true;
                    processedPosition.tireInfo = {
                        // 确保ID字段被正确提取
                        id: position.id || (position.tireInfo ? position.tireInfo.id : null),
                        tireNumber: position.tireNumber || (position.tireInfo ? position.tireInfo.tireNumber : null),
                        tireBrand: position.tireBrand || (position.tireInfo ? position.tireInfo.tireBrand : null),
                        tireModel: position.tireModel || (position.tireInfo ? position.tireInfo.tireModel : null),
                        transportCompany: position.transportCompany || (position.tireInfo ? position.tireInfo.transportCompany : null),
                        currentMileage: position.currentMileage || position.installMileage ||
                            (position.tireInfo ? position.tireInfo.currentMileage : null),
                        installDate: position.installDate || (position.tireInfo ? position.tireInfo.installDate : null)
                    };

                    // 调试日志
                    console.log(`处理轮胎ID: ${processedPosition.tireInfo.id} for ${processedPosition.positionKey}`);
                }

                return processedPosition;
            }).filter(item => item !== null);

            console.log('最终处理结果:', result);
            return result;
        }

        // 添加缺失的 renderTrailer 方法
        renderTrailer() {
            const container = document.getElementById('trailerContainer');

            // 清除现有的轮胎标记
            document.querySelectorAll('.tire-position').forEach(el => el.remove());

            if (this.tireData.length === 0) {
                this.showError('该拖车没有轮胎数据或数据格式不正确');
                return;
            }

            // 渲染所有轮胎位置
            this.tireData.forEach(position => {
                const tireElement = this.createTireElement(position);
                if (tireElement) {
                    container.appendChild(tireElement);
                }
            });

            // 更新标题显示车牌
            document.querySelector('.header h1').textContent = `🚛 轮胎可视化管理系统 - ${this.currentPlate}`;
        }

        // 添加缺失的 createTireElement 方法
        createTireElement(position) {
            if (!position.x || !position.y) {
                console.warn('位置坐标缺失:', position);
                return null;
            }

            const element = document.createElement('div');
            element.className = 'tire-position';
            element.style.left = position.x + 'px';
            element.style.top = position.y + 'px';
            element.title = position.positionKey;

            if (position.hasTire && position.tireInfo) {
                const tire = position.tireInfo;
                element.innerHTML = `
          <div class="tire-number">${tire.tireNumber || '未知编号'}</div>
          <div class="tire-position-label">${position.tirePosition}</div>
        `;
                element.classList.add('has-tire');

                // 根据里程判断状态
                const mileage = tire.currentMileage || 0;
                if (mileage > 200000) {
                    element.classList.add('danger');
                } else if (mileage > 100000) {
                    element.classList.add('warning');
                }
            } else {
                element.innerHTML = `
          <div class="empty-tire">无轮胎</div>
          <div class="tire-position-label">${position.tirePosition}</div>
        `;
            }

            element.addEventListener('click', () => {
                this.showTireInfo(position);
            });

            return element;
        }

        // 修改 showTireInfo 方法中的按钮部分
        showTireInfo(position) {
            const panel = document.getElementById('infoPanel');
            const details = document.getElementById('tireDetails');

            if (position.hasTire && position.tireInfo) {
                const tire = position.tireInfo;

                // 构建详情HTML
                let detailHtml = `
          <div class="info-item">
            <span class="info-label">位置：</span>
            <span class="info-value">${position.positionKey}</span>
          </div>
          <div class="info-item">
            <span class="info-label">轮胎编号：</span>
            <span class="info-value">${tire.tireNumber || '未知'}</span>
          </div>
          <div class="info-item">
            <span class="info-label">品牌型号：</span>
            <span class="info-value">${(tire.tireBrand || '')} ${(tire.tireModel || '')}</span>
          </div>
          <div class="info-item">
            <span class="info-label">运输公司：</span>
            <span class="info-value">${tire.transportCompany || '未知'}</span>
          </div>
          <div class="info-item">
            <span class="info-label">当前里程：</span>
            <span class="info-value">${tire.currentMileage ? tire.currentMileage.toLocaleString() + '公里' : '未知'}</span>
          </div>
          <div class="info-item">
            <span class="info-label">安装日期：</span>
            <span class="info-value">${tire.installDate || '未知'}</span>
          </div>`;

                // 使用ID跳转
                if (tire.id) {
                    detailHtml += `<button class="action-btn" onclick="viewTireDetailById('${tire.id}')">查看详细记录</button>`;
                } else {
                    detailHtml += `<button class="action-btn" disabled>无法查看详情（缺少轮胎ID）</button>`;
                }

                details.innerHTML = detailHtml;
            } else {
                details.innerHTML = `
          <div class="info-item">
            <span class="info-label">位置：</span>
            <span class="info-value">${position.positionKey}</span>
          </div>
          <div class="no-tire">该位置暂无轮胎</div>
          <button class="action-btn" onclick="addTire('${position.axleNumber}', '${position.tirePosition}')">
            为此位置添加轮胎
          </button>
        `;
            }

            panel.style.display = 'block';
        }

        showLoading(show) {
            const loadingIndicator = document.getElementById('loadingIndicator');
            loadingIndicator.style.display = show ? 'block' : 'none';
        }

        showError(message) {
            const errorElement = document.getElementById('errorMessage');
            errorElement.textContent = message;
            errorElement.style.display = 'block';
        }

        hideError() {
            const errorElement = document.getElementById('errorMessage');
            errorElement.style.display = 'none';
        }
    }

    // 全局实例
    const tireViz = new TireVisualization();

    // 全局函数
    function loadTrailer() {
        const plateInput = document.getElementById('plateInput');
        const plateNumber = plateInput.value.trim();

        if (!plateNumber) {
            alert('请输入车牌号');
            plateInput.focus();
            return;
        }

        tireViz.loadTrailer(plateNumber);
    }

    function closeInfoPanel() {
        document.getElementById('infoPanel').style.display = 'none';
    }

    function addTire(axleNumber, tirePosition) {
        if (confirm(`是否要为 ${axleNumber}轴${tirePosition} 添加轮胎？`)) {
            window.open(`/api/tires/add?trailerPlate=${tireViz.currentPlate}&axle=${axleNumber}&position=${tirePosition}`);
        }
    }

    // 修改全局函数，添加使用ID跳转的函数
    function viewTireDetailById(tireId) {
        if (tireId) {
            window.open(`/api/tires/${tireId}`);
        } else {
            alert('轮胎ID不存在，无法查看详情');
        }
    }

    function viewTireDetail(tireNumber) {
        window.open(`/api/tires/${tireNumber}`);
    }

    // 回车键搜索
    document.getElementById('plateInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            loadTrailer();
        }
    });

    // 车牌号自动补全功能
    $(document).ready(function() {
        $("#plateInput").autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: "/api/tires/autocomplete/plate-numbers",
                    dataType: "json",
                    data: {
                        term: request.term
                    },
                    beforeSend: function() {
                        $("#plateInput").addClass("ui-autocomplete-loading");
                    },
                    success: function(data) {
                        response(data);
                    },
                    error: function() {
                        response([]);
                    },
                    complete: function() {
                        $("#plateInput").removeClass("ui-autocomplete-loading");
                    }
                });
            },
            minLength: 1, // 输入1个字符就开始联想
            delay: 300, // 延迟300毫秒
            select: function(event, ui) {
                // 当用户选择联想项时，自动填充完整的车牌号
                $("#plateInput").val(ui.item.value);
                return false; // 阻止默认行为
            },
            focus: function(event, ui) {
                // 防止在焦点移动时更改输入框的值
                event.preventDefault();
            }
        });

        // 输入框获得焦点时自动选择所有文本，方便用户重新输入
        $("#plateInput").focus(function() {
            $(this).select();
        });
    });

    window.addEventListener('load', function() {
        document.getElementById('plateInput').focus();
    });
</script>
</body>
</html>